<?php
namespace app\api\controller;

use think\Controller;
use think\Session;
use app\api\controller\Speech;
use app\api\controller\Pinyin;

/**
 * 通用上传接口
 * Class Upload
 * @package app\api\controller
 */
class Upload extends Controller
{
    protected function _initialize()
    {
        parent::_initialize();
        if (!Session::has('admin_id')) {
            $result = [
                'error'   => 1,
                'message' => '未登录'
            ];

            return json($result);
        }
    }

    /**
     * 通用图片上传接口
     * @return \think\response\Json
     */
    public function upload()
    {
        $config = [
            'size' => 2097152,
            'ext'  => 'jpg,gif,png,bmp,aac'
        ];

        $file = $this->request->file('file');

        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $save_path   = '/uploads/';
        $info        = $file->validate($config)->move($upload_path);

        if ($info) {
            $result = [
                'error' => 0,
                'url'   => str_replace('\\', '/', $save_path . $info->getSaveName())
            ];
        } else {
            $result = [
                'error'   => 1,
                'message' => $file->getError()
            ];
        }

        return json($result);
    }

    /**
     * 小程序音频上传接口
     * @return \think\response\Json
     */
    public function upload_radio(){
        $config = [
            'size' => 2097152,
            'ext'  => 'aac,mp3'
        ];

        $file = $this->request->file('file');



        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $save_path   = '/uploads/';
        $info        = $file->validate($config)->move($upload_path);

        if ($info) {
            $name = date('Ymd').DS.md5(microtime(true)).".wav";
            $from = $_SERVER['DOCUMENT_ROOT'].$save_path.$info->getSaveName();
            $to = $_SERVER['DOCUMENT_ROOT'].$save_path;
            // $str = "ffmpeg -i ".$from." -y -f mjpeg -ss 3 -t 1 -s 740x500 ".$to.$name;  
            $str = "/usr/local/bin/ffmpeg -i ".$from." -ac 1 -ar 8000 ".$to.$name;
            system($str);
            $speech = new Speech();
            $pinyin = new Pinyin();
            $dis_path = 'uploads/'.$name;
            $res = $speech->radio_distinguish($dis_path,'wav',8000);
            $result = $pinyin->encode($res['result'][0],'head');
            

            // $result = [
            //     'error' => 0,
            //     'url'   => str_replace('\\', '/', $save_path . $info->getSaveName())
            // ];
        } else {
            $result = [
                'error'   => 1,
                'message' => $file->getError()
            ];
        }

        return json(['radioPath'=>$save_path.$info->getSaveName(),'pinyin'=>$result]);
    }
}